const portfinder = require('portfinder');
const chalk = require('chalk');
const { spawn } = require('child_process');

// Set the base port to 1212
portfinder.basePort = 1212;

const findFreePort = async () => {
  try {
    const port = await portfinder.getPortPromise();
    console.log(chalk.green(`Port ${port} is available.`));
    return port;
  } catch (err) {
    console.error(chalk.red('找不到可用端口-no port to start'));
    process.exit(1);
  }
};

const main = async () => {
  const port = await findFreePort();
  process.env.PORT = port;
  console.log(chalk.blue(`Using port ${port}`));

  // Spawn webpack with the found port
  spawn('npm', ['run', 'start:renderer'], {
    env: { ...process.env, PORT: port },
    stdio: 'inherit',
    shell: true,
  });
};

main();
